package com.i2863.tools.weixinmp.controller;


import com.i2863.tools.weixinmp.domain.NewsInfo;
import com.i2863.tools.weixinmp.domain.SiteArea;
import com.i2863.tools.weixinmp.domain.Weixin;
import com.i2863.tools.weixinmp.service.NewsService;
import com.i2863.tools.weixinmp.service.SiteAreaService;
import com.i2863.tools.weixinmp.service.WeixinService;
import com.i2863.tools.weixinmp.task.WeixinMpNotice;
import com.i2863.tools.weixinmp.util.NewsTemplate;
import com.i2863.tools.weixinmp.util.RedisQueueUtils;
import com.i2863.tools.weixinmp.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by xuweiwei on 2017/5/4.
 */
@Controller
@RequestMapping("/")
public class ApiController {


    private static Logger log = LoggerFactory.getLogger(ApiController.class);
    @Autowired
    private WeixinService weixinService;
    @Autowired
    private NewsService newsService;
    @Autowired
    private SiteAreaService siteAreaService;

    public static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");


    @ResponseBody
    @RequestMapping(value = "/spider")
    public Object spider(Integer siteId) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            List<Weixin> weixinList = weixinService.getWeixinByArea(siteId, null, null);
            for (Weixin weixin : weixinList) {
                weixin.setCount(1);
                weixin.setRec(true);
                weixin.setMatrix(false);
                RedisQueueUtils.insert("weixin:code", weixin);
            }
            result.put("code", 0);
            result.put("message", "success");
        } catch (Exception e) {
            result.put("code", 1);
            result.put("message", "fail");
        }

        return result;
    }


    @RequestMapping(value = "/userlogin")
    public void login(@RequestParam(value = "username", required = true) String username,
                      @RequestParam(value = "password", required = true) String password,
                      HttpServletRequest req, HttpServletResponse resp
    ) throws IOException {
        if ("i2863".equals(username) && "123456".equals(password)) {
            req.getSession().setAttribute("username", "i2863");
            resp.sendRedirect("/");
        } else if ("i2863".equals(username) && "111111".equals(password)) {
            req.getSession().setAttribute("username", "i2863");
            resp.sendRedirect("/upload.html");
        } else {
            resp.sendRedirect("/login.html");
        }

        return;
    }


    @ResponseBody
    @RequestMapping(value = "/search")
    public Object search(@RequestParam(value = "keyword", required = true) String keyword,
                         @RequestParam(value = "page", required = true) Integer page
    ) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            Map<String, Object> map = WeixinMpNotice.parseWeixin(keyword, page);
            result.put("code", 0);
            result.put("message", "success");
            result.putAll(map);
        } catch (Exception e) {
            result.put("code", 1);
            result.put("message", "fail");
            log.error("搜索公众号错误", e);
        }

        return result;
    }


    @ResponseBody
    @RequestMapping(value = "/add")
    public Object add(@RequestParam(value = "name", required = true) String name,
                      @RequestParam(value = "code", required = true) String code,
                      @RequestParam(value = "siteId", required = false) Integer siteId,
                      @RequestParam(value = "province", required = false) String province,
                      @RequestParam(value = "city", required = false) String city

    ) {

        Map<String, Object> result = new HashMap<String, Object>();
        try {
            Weixin wx = weixinService.getWeixinByCode(code);
            if (wx != null) {
                result.put("code", 2);
                result.put("message", "该微信公众号已添加.  省份:" + StringUtils.filter(wx.getCity()) + "    城市:" + StringUtils.filter(wx.getProvince()) + "    站点:" + StringUtils.filter(wx.getSiteId()));
                return result;
            }
            weixinService.save(name, code, siteId, province, city);
            result.put("code", 0);
            result.put("message", "success");
        } catch (Exception e) {
            result.put("code", 1);
            result.put("message", "fail");
            log.error("添加微信号出错", e);
        }

        return result;
    }

    @ResponseBody
    @RequestMapping(value = "/del")
    public Object del(
            @RequestParam(value = "code", required = true) String code
    ) {

        Map<String, Object> result = new HashMap<String, Object>();
        try {
            weixinService.delete(code);
            result.put("code", 0);
            result.put("message", "success");
        } catch (Exception e) {
            result.put("code", 1);
            result.put("message", "fail");
            log.error("删除微信号出错", e);
        }

        return result;
    }


    @ResponseBody
    @RequestMapping(value = "/list")
    public Object list() {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            List<Weixin> weixinList = weixinService.getAllWeixin();
            List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
            for (Weixin w : weixinList) {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("code", w.getCode());
                map.put("name", w.getName());
                list.add(map);
            }
            result.put("code", 0);
            result.put("message", "success");
            result.put("data", list);
        } catch (Exception e) {
            result.put("code", 1);
            result.put("message", "fail");
            log.error("获取微信公众号列表错误", e);
        }
        return result;
    }


    @ResponseBody
    @RequestMapping(value = "/mpList")
    public Object mpList(@RequestParam(value = "value", required = true) String value,
                         @RequestParam(value = "type", required = true) Integer type
    ) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            Integer siteId = null;
            String province = null;
            String city = null;
            if (type == 1) {
                province = value;
            } else if (type == 2) {
                city = value;
            } else {
                siteId = Integer.parseInt(value);
            }

            List<Weixin> weixinList = weixinService.getWeixinByArea(siteId, province, city);
            List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
            for (Weixin w : weixinList) {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("code", w.getCode());
                map.put("name", w.getName());
                list.add(map);
            }
            result.put("code", 0);
            result.put("message", "success");
            result.put("data", list);
        } catch (Exception e) {
            result.put("code", 1);
            result.put("message", "fail");
            log.error("获取微信公众号列表错误", e);
        }
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "/siteList")
    public Object siteList() {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            List<SiteArea> areaList = siteAreaService.listSiteArea();
            List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
            for (SiteArea siteArea : areaList) {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("siteName", siteArea.getSiteName());
                map.put("siteId", siteArea.getSiteId());
                map.put("province", siteArea.getProvince());
                map.put("city", siteArea.getCity());
                list.add(map);
            }
            result.put("code", 0);
            result.put("message", "success");
            result.put("data", list);
        } catch (Exception e) {
            result.put("code", 1);
            result.put("message", "fail");
            log.error("获取站点集合失败", e);
        }
        return result;
    }


    @ResponseBody
    @RequestMapping(value = "/getNews")
    public Object getWeixin(@RequestParam(value = "name", required = true) String name) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            List<NewsInfo> newsInfoList = newsService.getNewsBySource("公众号-" + name);
            List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
            for (NewsInfo info : newsInfoList) {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("title", info.getTitle());
                map.put("url", "/getNewsById?id=" + info.getId());
                map.put("newsTime", sdf.format(info.getNewsTime()));
                list.add(map);
            }
            result.put("code", 0);
            result.put("message", "success");
            result.put("data", list);
        } catch (Exception e) {
            result.put("code", 1);
            result.put("message", "fail");
            log.error("获取公众号文章列表错误", e);
        }
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "/getNewsById")
    public Object getNewsById(@RequestParam(value = "id", required = true) Integer id) {
        String html = "";
        try {
            NewsInfo newsInfo = newsService.getNewsInfoById(id);
            html = NewsTemplate.getHTML(newsInfo);
        } catch (Exception e) {
            log.error("获取公众号文章列表错误", e);
        }
        return html;
    }


}
